/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package io.iec.edp.caf.rpc.interceptor;

import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.interceptor.security.AccessDeniedException;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.transport.http.AbstractHTTPDestination;
import javax.servlet.http.HttpServletRequest;

/**
 * 自定义Cxf-Server端拦截器在哪个阶段实施拦截
 * @author wangyandong
 * @date 2021/06/03 16:15
 * @email wangyandong@inspur.com
 * https://blog.csdn.net/lzwjavaphp/article/details/14224899
 * 参考内置类型：org.apache.cxf.interceptor.security.SimpleAuthorizingInterceptor
 */
public class AuthorizingInterceptor extends AbstractPhaseInterceptor {

    public AuthorizingInterceptor() {
        //拦截器在调用方法之前拦截SOAP消息
        super(Phase.PRE_INVOKE);
    }

    /**
     * @Description: 拦截器操作
     * @param msg 被拦截到的消息
     * @throws Fault
     */
    @Override
    public void handleMessage(Message msg) throws Fault {
        //如果是请求者，则直接返回
        if(isRequestor(msg))
            return;

        HttpServletRequest request = (HttpServletRequest)msg.get(AbstractHTTPDestination.HTTP_REQUEST);
        if(request==null)
            throw new RuntimeException("invalid request");

        String userAgent = request.getHeader("User-Agent");
        if(userAgent.contains("CXF") == false){
            throw new AccessDeniedException("this API only use in iGIX，request deny");
        }
    }
}
